import React, { useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { FolderOutlined, FileOutlined } from '@ant-design/icons';
import './index.less';

interface FolderItem {
    id: string;
    name: string;
    type: 'folder' | 'file';
    children?: FolderItem[];
}

interface FolderNodeProps {
    item: FolderItem;
    level: number;
    onMove: (dragId: string, hoverId: string) => void;
}

const FolderNode: React.FC<FolderNodeProps> = ({ item, level, onMove }) => {
    const [{ isDragging }, drag] = useDrag({
        type: 'FOLDER_ITEM',
        item: { id: item.id, type: item.type },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    });

    const [{ isOver }, drop] = useDrop({
        accept: 'FOLDER_ITEM',
        drop: (draggedItem: { id: string; type: string }) => {
            if (draggedItem.id !== item.id && item.type === 'folder') {
                onMove(draggedItem.id, item.id);
            }
        },
        collect: (monitor) => ({
            isOver: monitor.isOver(),
        }),
    });

    const [isExpanded, setIsExpanded] = useState(true);

    return (
        <div
            ref={(node) => {
                drag(drop(node));
            }}
            className={`folder-node ${isDragging ? 'dragging' : ''} ${isOver ? 'drop-target' : ''}`}
            style={{ paddingLeft: `${level * 20}px` }}
        >
            <div className="folder-content">
                {item.type === 'folder' && (
                    <span
                        className="expand-icon"
                        onClick={() => setIsExpanded(!isExpanded)}
                    >
                        {isExpanded ? '▼' : '▶'}
                    </span>
                )}
                {item.type === 'folder' ? <FolderOutlined /> : <FileOutlined />}
                <span className="item-name">{item.name}</span>
            </div>
            {isExpanded && item.children && (
                <div className="children">
                    {item.children.map((child) => (
                        <FolderNode
                            key={child.id}
                            item={child}
                            level={level + 1}
                            onMove={onMove}
                        />
                    ))}
                </div>
            )}
        </div>
    );
};

const FolderMenu: React.FC = () => {
    const [folderStructure, setFolderStructure] = useState<FolderItem[]>([
        {
            id: '/testCases/脚本用例',
            name: '脚本用例',
            type: 'folder',
            children: [
                {
                    id: '/testCases/脚本用例/基本功能演示',
                    name: '基本功能演示',
                    type: 'folder',
                    children: [
                        { id: '/testCases/脚本用例/演示元素拖拽.json', name: '演示元素拖拽', type: 'file' },
                        { id: '/testCases/脚本用例/演示ifElse.json', name: '演示ifElse', type: 'file' },
                    ],
                },
                {
                    id: '/testCases/脚本用例/高级功能演示',
                    name: '高级功能演示',
                    type: 'folder',
                    children: [
                        { id: '/testCases/脚本用例/高级功能演示/演示多页签.json', name: '演示多页签', type: 'file' },
                        { id: '/testCases/脚本用例/高级功能演示/演示多iframe.json', name: '演示多iframe', type: 'file' },
                        { id: '/testCases/脚本用例/高级功能演示/演示多窗口.json', name: '演示多窗口', type: 'file' },
                    ],
                },
                {
                    id: '/testCases/脚本用例/子用例',
                    name: '子用例',
                    type: 'folder',
                    children: [
                        { id: '/testCases/脚本用例/子用例/演示多页签.json', name: '演示多页签', type: 'file' },
                        { id: '/testCases/脚本用例/子用例/演示多iframe.json', name: '演示多iframe', type: 'file' },
                        { id: '/testCases/脚本用例/子用例/演示多窗口.json', name: '演示多窗口', type: 'file' },
                    ],
                },
            ],
        },
    ]);

    const findItem = (items: FolderItem[], id: string): FolderItem | null => {
        for (const item of items) {
            if (item.id === id) return item;
            if (item.children) {
                const found = findItem(item.children, id);
                if (found) return found;
            }
        }
        return null;
    };

    const removeItem = (items: FolderItem[], id: string): FolderItem[] => {
        return items.filter((item) => {
            if (item.id === id) return false;
            if (item.children) {
                item.children = removeItem(item.children, id);
            }
            return true;
        });
    };

    const addItem = (items: FolderItem[], targetId: string, itemToAdd: FolderItem): FolderItem[] => {
        return items.map((item) => {
            if (item.id === targetId) {
                return {
                    ...item,
                    children: [...(item.children || []), itemToAdd],
                };
            }
            if (item.children) {
                return {
                    ...item,
                    children: addItem(item.children, targetId, itemToAdd),
                };
            }
            return item;
        });
    };

    const handleMove = (dragId: string, hoverId: string) => {
        const draggedItem = findItem(folderStructure, dragId);
        if (!draggedItem) return;

        const newStructure = removeItem(folderStructure, dragId);
        setFolderStructure(addItem(newStructure, hoverId, draggedItem));
    };

    return (

        <div className="folder-menu">
            {folderStructure.map((item) => (
                <FolderNode
                    key={item.id}
                    item={item}
                    level={0}
                    onMove={handleMove}
                />
            ))}
        </div>

    );
};

export default FolderMenu; 